<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入优惠券名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="金额" prop="money" >
        <el-input
          v-model="queryParams.money"
          placeholder="请输入优惠券金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          :change="clickmoney()"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="deadline">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.deadline"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择有效期">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item label="服务分类" prop="typeId">-->
        <!--<el-input-->
          <!--v-model="queryParams.typeId"-->
          <!--placeholder="请选择服务分类"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="选择状态" clearable size="small" prop="status">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:coupon:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">

      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange" row-key="couponId"   default-expand-all  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券名称" align="center" prop="title" />
      <el-table-column label="优惠券金额" align="center" prop="money"/>
      <el-table-column label="满减" align="center" prop="needMoney" />
      <el-table-column label="优惠券数量" align="center" prop="total" />
      <el-table-column label="领券开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="领券结束时间" align="center" prop="stopTime" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.stopTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="有效期" align="center" prop="deadline" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.deadline }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="服务分类" align="center" prop="typeId" />-->
      <el-table-column label="状态" align="center" prop="status":formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:coupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:coupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="优惠券名称" prop="title" >
          <el-input v-model="form.title" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券金额" prop="money" >
          <el-input v-model="form.money" placeholder="请输入优惠券金额"  :change="clickmoney()" />
        </el-form-item>
        <el-form-item label="满减优惠" prop="needMoney">
          <el-input v-model="form.needMoney" placeholder="请输入必须满多少才可以使用" @keyup.native="clickmoney1()" />
        </el-form-item>
        <el-form-item label="剩余数量" prop="surplus" >
          <el-input v-model="form.surplus" placeholder="请输入剩余数量" onkeyup="value=value.replace(/[^\d]/g,'')"/>
        </el-form-item>
          <el-form-item label="优惠券分类" prop="parentTypeId">
            <treeselect  v-model="form.typeId" :options="typeOptions" placeholder="选择分类"  :normalizer="normalizer" @select="treeselectfun"  style="width: 200px;"/>
          </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input v-model="form.total" placeholder="请输入优惠券数量" onkeyup="value=value.replace(/[^\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="领券时间" required>
          <el-col :span="9">
            <el-form-item prop="startTime">
              <el-date-picker type="date"   v-model="form.startTime" value-format="yyyy-MM-dd"  format="yyyy 年 MM 月 dd 日" placeholder="选择日期"  style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">结束</el-col>
          <el-col :span="9">
            <el-form-item prop="stopTime">
              <el-date-picker type="date"  v-model="form.stopTime"  value-format="yyyy-MM-dd"  format="yyyy 年 MM 月 dd 日" placeholder="选择日期" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>


        <el-form-item label="有效期" prop="deadline">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.deadline"
            type="date"
            value-format="yyyy-MM-dd"
                          format="yyyy 年 MM 月 dd 日"
            placeholder="选择有效期">
          </el-date-picker>
        </el-form-item>
        <!--<el-form-item label="服务分类" prop="typeId">-->
          <!--<el-input v-model="form.typeId" placeholder="请选择服务分类" />-->
        <!--</el-form-item>-->
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="选择状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {list, listType, getType, delType, addType, updateType, exportType , treeselect  } from "@/api/system/type";
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon } from "@/api/system/coupon";
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { Treeselect },
  name: "Coupon",
  data() {
    return {
      // 遮罩层
      defaultProps: {
        children: 'children',
        label: 'typeName'
      },

      loading: true,
      // 选中数组
      ids: [],

      typeOptions:undefined,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      statusOptions:[],
      // 总条数
      total: 0,
      // 优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {

        parentTypeId: undefined,
        pageNum: 1,
        pageSize: 10,
        stopTime:undefined,
        title: undefined,
        money: undefined,
        needMoney: undefined,
        surplus: undefined,
        total: undefined,
        endTime: undefined,
        startTime: undefined,
        deadline: undefined,
        typeId: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });

  },
  methods: {
    clickmoney1:function(){
      var pricec =  '' + this.form.needMoney;
      pricec = pricec
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
      if (pricec.indexOf('.') < 0 && pricec != '') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        pricec = parseFloat(pricec);
      }
      this.form.needMoney = pricec;
    },
    clickmoney: function(){
      var price = '' + this.queryParams.money;
      price = price
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');



      var price1 =  '' + this.form.money;
      price1 = price1
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');


      if (price.indexOf('.') < 0 && price != '') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        price = parseFloat(price);
      }

      if (price1.indexOf('.') < 0 && price1 != '') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        price1 = parseFloat(price1);
      }


      this.queryParams.money = price;
      this.form.money = price1;


    },
    treeselectfun(e){
      console.log(e)
      this.form.sysModel = e.sysModel
    },
    normalizer(node){
      //去掉children=[]的children属性
      if(node.children && !node.children.length){
        delete node.children;
      }
      return {
        id: node.typeId,
        label:node.typeName,
        children:node.children
      }
    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      list().then(response => {
        this.typeOptions = response.data;
      })

    },
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stopTime:undefined,
        typeId:undefined,
        parentTypeId: undefined,
        couponId: undefined,
        title: undefined,
        money: undefined,
        needMoney: undefined,
        surplus: undefined,
        total: undefined,
        endTime: undefined,
        startTime: undefined,
        deadline: undefined,
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.couponId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const couponId = row.couponId || this.ids
      getCoupon(couponId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.couponId != undefined) {
            updateCoupon(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addCoupon(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponIds = row.couponId || this.ids;
      this.$confirm('是否确认删除优惠券编号为"' + couponIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCoupon(couponIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有优惠券数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCoupon(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
